package org.jground.rx.ui.zk.docu;

//import java.io.File;
//import java.io.FileInputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jground.dbfs.IDBFile;
import org.jground.dbfs.IDBFileService;
import org.jground.rx.RXLangStrings;
import org.jground.rx.RXSystem;
import org.jground.rx.ui.zk.UIStyles;
import org.jground.zk.zulX.HboxX;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Button;
import org.zkoss.zul.Filedownload;
import org.zkoss.zul.Html;
import org.zkoss.zul.Popup;

public class UIFileDownload extends HboxX implements EventListener {

    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private static Log logger = LogFactory.getLog(UIFileDownload.class);

    private Popup popup = new Popup();
    private Button downloadButton = new Button();
    private boolean downloadOk;
    private IDBFile file;
    private IDBFileService fileService = RXSystem.getInstance().getFileService();

    private static final RXLangStrings downloadTheFile = new RXLangStrings();
    static {
        downloadTheFile.setDefault("Download the file");
        downloadTheFile.add("en", "Download the file ");
        downloadTheFile.add("de", "Local speichern der Datei ");
    }

    public UIFileDownload() {
        //
        downloadButton.setImageContent(UIStyles.getInstance().getAImage(UIStyles.ImageKey.download16));
        downloadButton.addEventListener(Events.ON_CLICK, this);
        add(downloadButton);
        //
        add(popup);
    }

    public void setFile(IDBFile idbFile) {
        try {
             if (fileService.isAvailable(idbFile)==false) {
                Html html = new Html("File " + file.getName() + " not available for download!");
                html.setParent(popup);
                downloadButton.setTooltiptext("");
                downloadOk = false;
            } else {
            	this.file = idbFile;
                downloadOk = true;
                downloadButton.setTooltiptext(downloadTheFile + idbFile.getName());
            }
        } catch (Exception e) {
            logger.error(e, e);
        }
    }

    public void onEvent(Event event) throws Exception {
        if (event.getTarget() == downloadButton) {
            if (file == null || downloadOk == false) {
                popup.open(downloadButton);
            } else {
                try {
                    Filedownload.save(fileService.getInputStream(file), null, file.getName());
                } catch (Exception e) {
                    logger.error(e, e);
                }
            }
        }
    }
}
